package com.inventory.controllers;

import com.inventory.entities.Route;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Performs the CRUD functionality for Routes relation in the database. Uses
 * container managed transactions.
 * @author sithum
 */
@Stateless(mappedName="RoutesController")
public class RoutesControllerBean implements RoutesControllerRemote {
    
    /*
     * Injects the specified Persistence unit to the EntityManager associated
     * with the current transaction.
     */
    @PersistenceContext(unitName = "SaicssPU")
    private EntityManager em;

    /**
     * Create records in the Routes relation.
     * @param categoryList
     */
    public void create(List<Route> routesList) {
        for (Route route : routesList) {
            em.persist(route);
            em.flush();
        }
    }

    /**
     * Updates an existing record in the Routes relation in the database.
     * @param routesList
     */
    public void edit(List<Route> routesList) {
        for (Route route : routesList) {
            em.persist(em.merge(route));
        }
    }

    /**
     * Remove set of records from the database Routes relation.
     * @param java.util.List
     * @throws java.lang.Exception
     */
    public void delete(List<Object> routesList) throws Exception {
        for (Object routeName : routesList) {
            Route route = findRouteByName(routeName.toString());
            if (route != null) {
                em.remove(em.merge(route));
            }
        }
    }

    /**
     * Returns the Route object by the given name.
     * @param java.lang.String categoryName - Name of the category
     * @return com.inventory.entities.Category
     */
    public Route findRouteByName(String routeName) throws Exception {
        Query findByName = em.createNamedQuery("Route.findByRouteName").setParameter("routeName", routeName);
        return (Route) findByName.getSingleResult();
    }

    /**
     * Return all the records in the Route relation.
     * @return
     */
    public List<Route> findAll() {
        return em.createNamedQuery("Route.findAll").getResultList();
    }

    public int count(){
        return Integer.valueOf(em.createNamedQuery("Route.recordCount").getSingleResult().toString()).intValue();
    }

}
